#pragma once
#include <iostream>
#include <vector> 
#include <algorithm>
#include <functional> // greater和less的头文件
using namespace std;
namespace rtx
{
	// Compare进行比较的仿函数 less->大堆
	// Compare进行比较的仿函数 greater->小堆
	template<class T, class Container = vector<T>,class Compare = less<T>>
	class priority_queue
	{
	public:
		priority_queue()
		{}

		template<class InputIterator>
		priority_queue(InputIterator first, InputIterator last)
			:_con(first,last) // 初始化列表初始化代替下面被注释的
		{
			//while (first != last)
			//{
			//	_con.push_back(*first);
			//	++first;
			//}
			for (int i = (_con.size() - 1 - 1) / 2;i >= 0;--i)
			{
				adjust_down(i);
			}
		}

		void push(const T& x)
		{
			_con.push_back(x);
			adjust_up(_con.size() - 1);
		}

		void adjust_up(size_t child)
		{
			Compare cmp;

			size_t father = (child - 1) / 2;
			while (child > 0)
			{
				//if (_con[father] < _con[child])
				if (cmp(_con[father], _con[child]))//仿函数想函数一样使用
				{
					swap(_con[father], _con[child]);
					child = father;// 交换后向上走
					father = (child - 1) / 2;
				}
				else
				{
					break;
				}
			}
		}

		void pop()
		{
			std::swap(_con[0], _con[_con.size() - 1]);
			_con.pop_back();

			adjust_down(0);
		}

		void adjust_down(size_t father)
		{
			Compare cmp;
			size_t child = father * 2 + 1;// 默认左孩子大
			while (child < _con.size())
			{
				//if (child + 1 < _con.size() && _con[child] < _con[child + 1])
				if (child + 1 < _con.size() && cmp(_con[child], _con[child + 1]))//先考虑右孩子是否存在
				{
					child += 1;
				}
				//if (_con[child] > _con[father]) 这里写了大于，所以是不好的(下次一定)
				if (cmp(_con[father], _con[child]))
				{
					swap(_con[child], _con[father]);
					father = child;
					child = father * 2 + 1;
				}
				else
				{
					break;
				}
			}
		}

		const T& top()
		{
			return _con[0];
		}

		bool empty()  const
		{
			return _con.empty();
		}

		size_t size() const
		{
			return _con.size();
		}

	private:
		Container _con;
	};
}